package com.suray.wcs.service.scheduling;

import com.suray.basic.wcs.plc.core.Plc;
import com.suray.basic.wcs.plc.core.PlcWordCache;
import com.suray.basic.wcs.plc.pojo.DeviceBase;
import com.suray.basic.wcs.plc.pojo.PlcParam;
import com.suray.basic.wcs.plc.utils.NetAddress;
import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.basic.wcs.utils.WcsFuncUtil;
import com.suray.wcs.service.system.entity.PlcDB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class PlcReadTimer {
    private PlcDB plcModel;
    private List<DeviceBase> deviceParams;
    private Logger log = LoggerFactory.getLogger(this.getClass());

    public PlcReadTimer(PlcDB plcModel, List<DeviceBase> plc_device) {
        this.plcModel = plcModel;
        this.deviceParams = plc_device;
    }

    public void start() {
        if (deviceParams.size() == 0) {
            LoggerUtil.warn(plcModel.getPlcName() + " 没检测到设备,不创建PLC", this.getClass());
            return;
        }
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleWithFixedDelay(() -> {
            try {
                refreshStatus();
            } catch (IOException e) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                log.warn(plcModel.getPlcName() + "PLC通讯异常");
            } catch (Exception e){
                WcsFuncUtil.exceptionLog(e, this.getClass());
            }
        }, 0, PlcWordCache.UPDATE_CATCH_TIME, TimeUnit.MILLISECONDS);
        //每秒更新一次缓存
        log.info("PLC轮询线程启动");
    }

    private void refreshStatus() throws IOException {
        Plc.getPlc(new NetAddress(plcModel.getPlcIp(), plcModel.getPlcPort()), deviceParams,
                new PlcParam(plcModel.getPlcStartNum(), plcModel.getPlcMaxNum(),plcModel.getPlcName())).refreshCache();
    }
}
